import { tunnyRequest as request } from '@/utils/request';
import { Message } from 'element-ui';
import { decodeToken, decrypt, encrypt } from '@/utils/auth';

// import { AppModule } from "@/store/modules/app";
// import { createService } from "@/utils/request";

// const request = (option: any) => createService(AppModule.baseURL)(option);

// 获取登入账号的认证模式、系统版本号等
export const apiGetPublicSettings = () => {
  return request({
    url: '/settings',
    method: 'get'
  });
}

export const apiGetDownloads = () => {
  return request({
    url: '/downloads/',
    method: 'get'
  });
}

// 获取用户列表
export const apiGetUserList = () => {
  return request({
    url: '/users/summary',
    method: 'get'
  });
}

// 获取token登陆
export const login = (data: any) => {
  return request({
    url: '/token/get',
    method: 'post',
    data
  });
}

/**
 *获取用户配置
  */
export const apiGetUserSettings = (data: any) => {
  return request({
    url: "/tunny_settings",
    method: "get"
  });
}

/**
 *修改用户配置
  */
 export const apiPutUserSettings = (data: any) => {
  return request({
    url: "/tunny_settings/",
    method: "PATCH",
    data: {
      settings:data
    }
  });
}

// 周期性间隔刷新token
export const apiRefreshToken = (token: string) => {
  return request({
    url: '/token/refresh',
    method: 'post',
    data: {
      token: token
    }
  });
}

// 查看本token用户详情
export const apiGetSelfUser = () => {
  return request({
    url: 'cloud_tenants/self',
    method: 'get'
  }).then((res: any) => {
    if (res.error) {
      // Message.warning(res.message);
    } else {
      return res;
    }
  });
}

// 查看本token系统用户详情
export const apiGetSystemUser = async () => {
  const res: any = await request({
    url: 'users/self',
    method: 'get'
  });
  if (res.error) {
    Message.warning(res.message);
    return res;
  }
  if(res.email) {
    res.email = decrypt(res.email);
  }
  if(res.mobile) {
    res.mobile = decrypt(res.mobile);
  }
  if(res.telephone) {
    res.telephone = decrypt(res.telephone);
  }
  if(res.username) {
    res.username = decrypt(res.username);
  }
  return res;
}


// 登出
export const logout = () => {
  return request({
    url: '/logout',
    method: 'post'
  });
}

export const apiListUsersPaged = async (params: any = {}): Promise<any> => {
  if (params.pageSize) params.page_size = params.pageSize;
  const result: any = await request({
    url: "/users",
    method: 'GET',
    params
  });
  return result;
}

// 查看用户组列表
export const apiListUserGroupsPaged = (params: any) => {
  return request({
    url: '/user_groups',
    method: 'get',
    params
  });
}

// 增加用户
export const apiAddUser = (params: any) => {
  return request({
    url: '/users',
    method: 'post',
    data: params
  });
}

// 查看所有用户名称列表,防止用户重名
export const apiCreateUsers = (params: any) => {
  return request({
    url: '/users',
    method: 'post',
    data: params
  });
}

// 删除用户
export const apiDeleteUsers = async (id: any) => {
  try {
    // await apiDeleteIdvhostAuths({ auth_type: "user", auth_id: id });
    return request({
      url: '/users/' + id,
      method: 'delete'
    });
  } catch (error) {
    return Promise.reject(error);
  }
}

// 查看所有已经存在的用户名
export const apiGetAllUserNames = () => {
  return request({
    url: '/users/names/used',
    method: 'get'
  });
}

// 查看某用户组下还未被添加的用户
export const apiListUserGroupAbsentUsers = (id: any) => {
  return request({
    url: 'user_groups/' + id + '/absentusers',
    method: 'get'
  });
}

// 查看某用户组下的用户列表
export const apiListUserGroupUsersPaged = (id: number, query: any) => {
  return request({
    url: 'user_groups/' + id + '/users?page=' + query.page + '&page_size=' + query.page_size + '&search=' + query.search,
    method: 'get'
  });
}

// 增加某用户组下的用户
export const apiAddUserGroupUser = (userGroupId: string, user: any) => {
  return request({
    url: 'user_groups/' + userGroupId + '/users',
    method: 'post',
    data: user
  });
}

// 删除某用户组下的用户
export const apiDeleteUserGroupUser = (userGroupId: string, userId: string) => {
  return request({
    url: 'user_groups/' + userGroupId + '/users/' + userId,
    method: 'delete'
  });
}

// 删除某用户组下的用户
export const apiGetUserDetail = (userId: string) => {
  return request({
    url: 'users/' + userId,
    method: 'get'
  });
}

// 修改用户
export const apiUpdateUser = (id: string, params: any) => {
  return request({
    url: '/users/' + id,
    method: 'patch',
    data: params
  });
}

// 是否激活当前用户为超级用户
export const apiSuperUser = (id: string, isSuperuser: boolean) => {
  return request({
    url: '/users/' + id,
    method: 'patch',
    data: {
      is_superuser: isSuperuser
    }
  });
}

// 是否激活当前用户
export const apiActivateUser = (id: string, isActive: boolean) => {
  return request({
    url: '/users/' + id,
    method: 'patch',
    data: {
      is_active: isActive
    }
  });
}

// 查看所有用户
export const apiListUsers = (search = '') => {
  return request({
    url: '/users?' + '&search=' + search,
    method: 'get'
  });
}

// 查看所有用户组
export const apiListUserGroups = (search = '') => {
  return request({
    url: '/user_groups?&search=' + search,
    method: 'get'
  });
}

// 获取ldap配置
export const apiGetLdapConfig = () => {
  return request({
    url: '/ldap/config',
    method: 'get'
  });
}

// 更新ldap配置
export const apiUpdateLdapConfig = (data: any) => {
  return request({
    url: "/ldap/config",
    method: "patch",
    data
  });
}

// 获取ldap组织列表
export const apiGetLdapOrgnizationList = (dn = '') => {
  return request({
    url: `/ldap/organizationals?dn=${encodeURIComponent(dn)}`,
    method: "get"
  });
}

// 获取ldap用户列表
export const apiGetLdapUserList = (dn = '', search = "") => {
  return request({
    url: `/ldap/users?dn=${encodeURIComponent(dn)}&search=${search}`,
    method: "get"
  });
}

// 查看所有用户名称列表,防止用户重名
export const apiImportLdapUsers = (ldapUsers: any) => {
  return request({
    url: '/ldap/import_users',
    method: 'post',
    data: {
      ldap_users: ldapUsers
    }
  });
}

// 查看所有用户名称列表,防止用户重名
export const apiGetThemeSettings = () => {
  return request({
    url: '/theme/setting',
    method: 'get'
  });
}

// 查看所有用户
export const apiGetAllBackendsUsers = () => {
  return request({
    url: '/users?hidden_internal=false',
    method: 'get'
  });
}

// 查看用户组织树结构
export const apiGetOrgnizationTree = async () => {
  function setLastLdap(tree: Array<any>, ldapIdTemporary: any) {
    tree.map((node: any) => {
      let _ldapId_temporary = ldapIdTemporary;
      if (node.backend === 'ldap') {
        _ldapId_temporary = node.id;
      } else {
        node.lastLdapId = _ldapId_temporary;
      }
      if (node.children && node.children.length > 0) {
        setLastLdap(node.children, _ldapId_temporary);
      }
    });
  }
  try {
    const result: any = await request({
      url: '/orgnizations/tree',
      method: 'get'
    });
    setLastLdap(result, "");
    return Promise.resolve(result);
  } catch (error) {
    return Promise.reject(error);
  }
}

// 创建用户组织
export const apiCreateOrgnization = (params: any) => {
  return request({
    url: '/orgnizations',
    method: 'post',
    data: params
  });
}

// 删除用户组织
export const apiDeleteOrgnization = async (id: string) => {
  // const res: any = await this.apiDeleteIdvhostAuths({ auth_type: "orgnization", auth_id: id })
  // if (res.status !== 200) {
  //   return res;
  // }
  return request({
    url: '/orgnizations/' + id,
    method: 'delete'
  });
}

// 查看用户组织树下用户
export const apiGetUsersByOrgnizationId = (orgnizationId: any, params: any = {}) => {
  return request({
    url: '/orgnizations/' + orgnizationId + '/users',
    method: 'get',
    params
  });
}

// 获取全部用户不分页
export const apiGetAllUsers = () => {
  return request({
    url: '/users?hidden_internal=false',
    method: 'get'
  });
}

// 获取全部用户组不分页
export const apiGetAllUserGroups = () => {
  return request({
    url: '/user_groups?hidden_internal=false',
    method: 'get'
  });
}

// 获取全部用户组织不分页
export const apiGetAllUserOrgnizations = () => {
  return request({
    url: '/orgnizations?hidden_internal=false',
    method: 'get'
  });
}

// 获取用户组织下级不分页
export const apiGetOrgnizationAllSubordinates = (id: string) => {
  return request({
    url: '/orgnizations?hidden_internal=false?parent_id=' + id,
    method: 'get'
  });
}

// 获取用户组织详情
export const apiGetOrgnizations = (id: string) => {
  return request({
    url: '/orgnizations/' + id,
    method: 'get'
  });
}

// 修改用户组织
export const apiUpdateOrgnizations = (id: string, params: any) => {
  return request({
    url: '/orgnizations/' + id,
    method: 'patch',
    data: params
  });
}

// 查看多因素配置
export const apiGetLdapSettings = () => {
  return request({
    url: '/settings',
    method: 'get'
  });
}

// 查看LDAP用户列表
export const apiListLdapUsersPaged = (limit: number, offset: any, search: string) => {
  return request({
    url: '/users?limit=' + limit + '&offset=' + offset + '&search=' + search + '&backend=ldap',
    method: 'get'
  });
}

// 查看用户详情
export const apiGetUser = (id: string) => {
  return request({
    url: '/users/' + id,
    method: 'get'
  });
}

export const apiGetCaptchaConfig = () => {
  return request({
    url: '/captcha/config',
    method: 'get'
  });
}

// 查看veriface配置
export const apiGetVerifaceConfig = () => {
  return request({
    url: '/veriface/config',
    method: 'get'
  });
}

// 查看fingerprint 指纹识别认证配置
export const apiGetFingerprintConfig = () => {
  return request({
    url: '/fingerprint/config',
    method: 'get'
  });
}

// 修改veriface配置
export const apiSetVerifaceConfig = (conf: any) => {
  return request({
    url: '/veriface/config',
    method: 'patch',
    data: conf
  });
}

// 修改fingerprint 指纹识别认证配置
export const apiSetFingerprintConfig = (conf: any) => {
  return request({
    url: '/fingerprint/config',
    method: 'patch',
    data: conf
  });
}

// 修改动态验证码配置
export const apiSetCaptchaConfig = (conf: any) => {
  return request({
    url: '/captcha/config',
    method: 'patch',
    data: conf
  });
}


export const changeSelfPassword = (params: any) => {
  return request({
    url: "/users/self",
    method: "patch",
    data: params
  });
}

export const checkSelfPassword = (credentials: any) => {
  return request({
    url: "/users/self/check_password",
    method: "POST",
    data: credentials
  });
}

export const getAllUsersSummary = () => {
  return request({
    url: "/users/summary",
    method: "GET"
  });
}

export const getAllUserGroupsSummary = () => {
  return request({
    url: "user_groups/summary",
    method: "GET"
  });
}

export const getAllOrgnizationsSummary = () => {
  return request({
    url: "orgnizations/summary",
    method: "GET"
  });
}


export const apiGetMultiFactorAuthentication = async () => {
  try {
    const captchaConfigResult = await apiGetCaptchaConfig();
    const verifaceConfigResult = await apiGetVerifaceConfig();
    const fingerprintConfigResult = await apiGetFingerprintConfig();

    return Promise.resolve({
      captchaConfig: captchaConfigResult,
      verifaceConfig: verifaceConfigResult,
      fingerprintConfig: fingerprintConfigResult
    });
  } catch (error) {
    return Promise.reject(error);
  }
}

export const apiSetMultiFactorAuthentication = async (config: any) => {
  try {
    await apiSetVerifaceConfig(config.verifaceConfig);
    await apiSetFingerprintConfig(config.fingerprintConfig);
    await apiSetCaptchaConfig(config.captchaConfig);

    return Promise.resolve();
  } catch (error) {
    return Promise.reject(error);
  }
}

/**
 * 获取多个角色
 * @param params 请求参数
 */
export const apiGetRoles = (params: any) => {
  return request({
    url: "roles",
    method: "GET",
    params
  });
}

/**
 * 新增角色
 * @param data 角色数据
 */
export const apiPostRoles = (data: any) => {
  return request({
    url: "roles",
    method: "POST",
    data
  });
}

/**
 * 删除角色
 * @param id 角色id
 */
export const apiDeleteRoles = (id: any) => {
  return request({
    url: "roles/" + id,
    method: "DELETE"
  });
}

/**
 * 修改角色
 * @param id 角色id
 * @param data 角色数据
 */
export const apiPatchRoles = (id: any, data: any) => {
  return request({
    url: "roles/" + id,
    method: "PATCH",
    data
  });
}

/**
 * 获取角色详情
 * @param id 角色id
 */
export const apiGetRoleInfo = (id: any) => {
  return request({
    url: "roles/" + id,
    method: "GET"
  });
}

/**
 * 获取角色已使用的名称，重名验证使用
 * @param id 角色id
 */
export const apiGetRoleUsedNames = () => {
  return request({
    url: "roles/names/used",
    method: "GET"
  });
}

/**
 * 获取已有此角色的用户
 * @param id 角色id
 */
export const apiGetRoleUsers = (id: any, params: any) => {
  return request({
    url: "/roles/" + id + "/users",
    method: "GET",
    params
  });
}

/**
 * 向角色中添加用户
 * @param id 角色id
 */
export const apiPostRoleUsers = (id: any, user: any) => {
  user.action = "add";
  return request({
    url: "/roles/" + id + "/users",
    method: "POST",
    data: user
  });
}

/**
 * 删除角色中的用户
 * @param id 角色id
 */
export const apiDeleteRoleUsers = (id: any, userId: any) => {
  return request({
    url: "/roles/" + id + "/users/" + userId,
    method: "DELETE"
  });
}

/**
 * 获取角色权限
 * @param id 角色的id
 */
export const apiGetRolesPermissions = (id: any) => {
  return request({
    url: "/roles/" + id + "/permissions",
    method: "GET"
  });
}

/**
 * 新增角色权限
 * @param id 角色的id
 */
export const apiPostRolesPermissions = (id: any, data: any) => {
  return request({
    url: "/roles/" + id + "/permissions",
    method: "POST",
    data
  });
}

/**
 * 获取角色中没有的用户列表
 * @param id 角色id
 */
export const apiGetRolesAbsentUsers = (id: any) => {
  return request({
    url: "/roles/" + id + "/absentusers",
    method: "GET"
  });
}

// 查看tunny配置
export const apiGetTunnySettings = () => {
  return request({
    url: '/tunny_settings/',
    method: 'get'
  });
}

// 设置tunny配置
export const apiEditTunnySettings = (data: any) => {
  return request({
    url: '/tunny_settings/',
    method: 'patch',
    data
  });
}

/**
 * 获取当前登录用户权限列表
 */
export const getUserPermission = async () => {
  return request({
    url: '/users/self/permissions',
    method: 'get'
  });
}

/**
 * 获取桌面用户列表
 */
export const getDesktopUserList = async (params: any) => {
  const res:any = await request({
    url: "/ad_accounts",
    method: 'GET',
    params
  });
  // (res.rows ? res.rows : res).forEach((row: any, rowsIndex: number) => {
  //   if (row.cloud_tenant_name) {
  //     row.cloud_tenant_name = decrypt(row.cloud_tenant_name);
  //   }
  //   if(row.email) {
  //     row.email = decrypt(row.email);
  //   }
  //   if(row.mobile) {
  //     row.mobile = decrypt(row.mobile);
  //   }
  //   if(row.name) {
  //     row.name = decrypt(row.name);
  //   }
  //   if(row.distinguished_name) {
  //     row.distinguished_name = decrypt(row.distinguished_name);
  //   }
  //   if(row.user_principal_name) {
  //     row.user_principal_name = decrypt(row.user_principal_name);
  //   }
  //   if(row.sam_account_name) {
  //     row.sam_account_name = decrypt(row.sam_account_name);
  //   }
  //   if(row.telephone) {
  //     row.telephone = decrypt(row.telephone);
  //   }
  //   (res.rows ? res.rows : res)[rowsIndex] = row;
  // });
  return res;
  // const rows = [];
  // for (let i = 0; i < 10; i++) {
  //   rows.push({
  //     id: i,
  //     ad_id: i,
  //     cloudtenant: `云租户${i}`,
  //     pretty_name: `桌面用户${i}`,
  //     name: `test${i}`,
  //     distinguishedName: `CN=test${i},OU=development,DC=astute-tec,DC=com`,
  //     displayName: `test${i}`,
  //     sAMAccountName: `test${i}`,
  //     userPrincipalName: `test${i}@astute-tec.com`,
  //     resource_pool_name: `资源池${i}`,
  //     resource_pool: i,
  //     resource_name: `Horizon${i}`
  //   });
  // }
  // if (params.page && params.page_size) {
  //   return {
  //     rows,
  //     total: 209
  //   }
  // } else {
  //   return rows;
  // }
}

/**
 * 获取系统管理员列表
 */
export const apiGetSystemManagerList = async (params: any) => {
  const res: any =  await request({
    url: '/users',
    method: 'GET',
    params
  });
  // (res.rows ? res.rows : res).forEach((row: any, rowsIndex: number) => {
  //   if (row.email) {
  //     row.email = decrypt(row.email);
  //   }
  //   if (row.mobile) {
  //     row.mobile = decrypt(row.mobile);
  //   }
  //   if (row.telephone) {
  //     row.telephone = decrypt(row.telephone);
  //   }
  //   if (row.username) {
  //     row.username = decrypt(row.username);
  //   }
  //   (res.rows ? res.rows : res)[rowsIndex] = row;
  // });
  return res;
  // const rows = [];
  // for (let i = 0; i < 10; i++) {
  //   rows.push({
  //     id: i,
  //     username: `系统管理员${i}`,
  //     department: `部门${i}`,
  //     position: `职位${i}`,
  //     auth_failed_at: null,
  //     auth_failed_times: 0,
  //     auth_time_window: "{\"start\": 0, \"end\": 1440}",
  //     mobilephone: '13777777777',
  //     telephone: '83334',
  //     email: '13777777777@cmss.com',
  //     description: "详细信息详细信息详细信息详细信息详细信息详细信息详细信息详细信息详细信息详细信息详细信息详细信息"
  //   });
  // }
  // if (params.page && params.page_size) {
  //   return {
  //     rows,
  //     total: 209
  //   }
  // } else {
  //   return rows;
  // }
}

/**
 * 获取客户管理员列表
 */
export const apiGetTenantManagerList = async (params: any) => {
  const rows = [];
  for (let i = 0; i < 10; i++) {
    rows.push({
      id: i,
      username: `客户管理员${i}`,
      department: `部门${i}`,
      position: `职位${i}`,
      auth_failed_at: null,
      auth_failed_times: 0,
      auth_time_window: "{\"start\": 0, \"end\": 1440}",
      mobilephone: '13777777777',
      telephone: '83334',
      email: '13777777777@cmss.com',
      description: "详细信息详细信息详细信息详细信息详细信息详细信息详细信息详细信息详细信息详细信息详细信息详细信息"
    });
  }
  if (params.page && params.page_size) {
    return {
      rows,
      total: 209
    }
  } else {
    return rows;
  }
}

/**
 * 获取系统管理员详情接口
 */
export const apiGetSystemManagerInfo = async (id: any) => {
  const res: any = await request({
    url: "/ad_accounts/" + id,
    method: "GET"
  });
  // if (res.cloud_tenant_name) {
  //   res.cloud_tenant_name = decrypt(res.cloud_tenant_name);
  // }
  // if(res.email) {
  //   res.email = decrypt(res.email);
  // }
  // if(res.mobile) {
  //   res.mobile = decrypt(res.mobile);
  // }
  // if(res.name) {
  //   res.name = decrypt(res.name);
  // }
  // if(res.distinguished_name) {
  //   res.distinguished_name = decrypt(res.distinguished_name);
  // }
  // if(res.user_principal_name) {
  //   res.user_principal_name = decrypt(res.user_principal_name);
  // }
  // if(res.sam_account_name) {
  //   res.sam_account_name = decrypt(res.sam_account_name);
  // }
  // if(res.telephone) {
  //   res.telephone = decrypt(res.telephone);
  // }
  return res;
}

/**
 * 获取租户管理员详情接口
 */
export const apiGetTenantManagerInfo = async (id: any) => {
  // console.log(id);
  return {
    id: id,
    username: `客户管理员${id}`,
    department: `部门${id}`,
    position: `职位${id}`,
    auth_failed_at: null,
    auth_failed_times: 0,
    auth_time_window: "{\"start\": 0, \"end\": 1440}",
    mobilephone: '13777777777',
    telephone: '83334',
    email: '13777777777@cmss.com',
    description: "详细信息详细信息详细信息详细信息详细信息详细信息详细信息详细信息详细信息详细信息详细信息详细信息"
  }
}

/**
 * 重置失败计数
 */
export const apiResetLoginFailCount = async (userList: Array<any>, data: any) => {
  for (let i = 0; i < userList.length; i++) {
    delete userList[i].password;
    delete userList[i].re_password;
    const reqData = Object.assign(userList[i], data);
    await request({
      url: `/ad_accounts/${userList[i].id}`,
      method: 'PATCH',
      data: data
    });
  }
  return true;
}

/**
 * 获取租户列表
 */
export const apiGetTenantList = async (params: any) => {
  const res: any  =  await request({
    url: "/cloud_tenants",
    method: "GET",
    params
  });
  // (res.rows ? res.rows : res).forEach((row: any, rowsIndex: number) => {
  //   if (row.name) {
  //     row.name = decodeToken(row.name);
  //   }
  //   (res.rows ? res.rows : res)[rowsIndex] = row;
  // });
  return res;
}

/**
 * 获取租户列表
 */
 export const apiGetTenantById = async (id: any) => {
  const res: any  =  await request({
    url: `/cloud_tenants/${ id }`,
    method: "GET",
  });
  return res;
}

/**
 * 获取租户列表
 */
 export const apiGetTenantListByPageSize = async (page: any, page_size: any, search_data?: any) => {
  return await request({
    url: "/cloud_tenants?page=" + page + "&page_size=" + page_size + "&search=" + search_data,
    method: "GET",
    params: {}
  });
}

/**
 * 创建租户
 */
export const apiPostTenant = async (formData: any) => {
  return await request({
    url: '/cloud_tenants',
    method: 'POST',
    data: {
      name: formData.name,
      // password: formData.password ? encrypt(formData.password) : null,
      description: formData.description
    }
  });
}

/**
 * 编辑租户
 */
export const apiPutTenant = async (id: any, formData: any) => {
  return await request({
    url: `/cloud_tenants/${id}`,
    method: 'PUT',
    data: {
      name: formData.name,
      password: formData.password,
      // password: encrypt(formData.password),
      description: formData.description
    }
  });
}

export const apiSetUserAlias = async (userType: any, userList: Array<any>, data: any) => {
  delete userList[0].user_principal_name;
  return await request({
    url: `/ad_accounts/${userList[0].id}`,
    method: 'PATCH',
    data: Object.assign(userList[0], data)
  })
}

// 绑定手机号
export const apiSetUserMobile = async (userType: any, userList: Array<any>, data: any) => {
  delete userList[0].user_principal_name;
  // data.mobile = encrypt(data.mobile);
  return await request({
    url: `/ad_accounts/${userList[0].id}`,
    method: 'PATCH',
    data: Object.assign(userList[0], data),
  })
}

//短信认证
export const apiSetUserSms = async (data: any) => {
  return await request({
    url:`ad_accounts/update/attrs`,
    method:'POST',
    data: data
  })
}
/**
 * 批量修改用户、管理员
 * @param userType desktop_user-桌面用户、system_admin-系统管理员、tenant_admin-租户管理员
 * @param userList 上述用户的列表
 * @param data 需要修改的数据
 */
export const apiBatchPutUser = async (userType: any, userList: Array<any>, data: any, setTime?: boolean) => {
  switch(userType) {
    case 'desktop_user':
      for (let i = 0; i < userList.length; i++) {
        delete userList[i].user_principal_name;
        if (setTime) {
          delete userList[i].pretty_name
        }
        await request({
          url: `/ad_accounts/${userList[i].id}`,
          method: 'PATCH',
          data: Object.assign(userList[i], data)
        });
      }
      break;
    case 'system_admin':
      for (let i = 0; i < userList.length; i++) {
        delete userList[i].cloud_tenant;
        delete userList[i].password;
        const reqData = Object.assign(userList[i], data);
        // data.email = encrypt(data.email);
        // data.mobile = encrypt(data.mobile);
        // data.telephone = encrypt(data.telephone);
        // data.username = encrypt(data.username);
        await request({
          url: `/users/${userList[i].id}`,
          method: 'PATCH',
          data
        });
      }
      break;
    case 'tenant_admin':
      for (let i = 0; i < userList.length; i++) {
        delete userList[i].password;
        delete userList[i].re_password;
        const reqData = Object.assign(userList[i], data);
        await request({
          url: `/cloud_tenants/${userList[i].id}`,
          method: 'PATCH',
          data: reqData
        });
      }
      break;
  }
  
  return true;
}

/**
 * 批量删除用户、管理员
 * @param userType desktop_user-桌面用户、system_admin-系统管理员、tenant_admin-租户管理员
 * @param userList 上述用户的列表
 */
export const apiBatchDeleteUser = async (userType: any, userList:Array<any>) => {
  switch(userType) {
    case 'desktop_user':
      for (let i = 0; i < userList.length; i++) {
        await request({
          url: `/ad_accounts/${userList[i].id}`,
          method: "DELETE"
        });
      }
      break;
    case 'system_admin':
      for (let i = 0; i < userList.length; i++) {
        await request({
          url: `/users/${userList[i].id}`,
          method: "DELETE"
        });
      }
      break;
    case 'tenant_admin':
      for (let i = 0; i < userList.length; i++) {
        await request({
          url: `/cloud_tenants/${userList[i].id}`,
          method: "DELETE"
        });
      }
      break;
  }
}

/**
 * 批量对用户或管理员做操作
 * @param userType desktop_user-桌面用户、system_admin-系统管理员、tenant_admin-租户管理员
 * @param itemList 上述用户数组
 * @param action 操作的类型
 */
export const apiBatchUserAction = async (userType: any, itemList: Array<any>, action: any, data: any) => {
  switch(userType) {
    case 'desktop_user':
      for (let i = 0; i < itemList.length; i++) {
        await request({
          url: `/ad_accounts/${itemList[i].id}/action`,
          method: "POST",
          data: {
            action: action,
            new_password: data ? encrypt(data.password) : undefined
          }
        })
      }
      break;
    case 'system_admin':
      for (let i = 0; i < itemList.length; i++) {
        await request({
          url: `/users/${itemList[i].id}/action`,
          method: "POST",
          data: {
            action: action
          }
        })
      }
      break;
  }
  return true;
}

export const apiGetActiveDirectorys = (params: any) => {
  return request({
    url: "/active_directories",
    method: 'GET',
    params
  });
}

// 概览
export const apiGetOverview = () => {
  return request({
    url: "/overviews/system",
    method: 'GET',
  });
}

// 概览-租户
export const apiGetOverviewTenant = () => {
  return request({
    url: "/overviews/tenant",
    method: 'GET',
  });
}

// 普通版桌面池-绑定到租户
export const apiPostInputDesktopInfo = (data: any, headers: any) => {
  return request({
    url: "/ad_accounts/update/cloud_tenant",
    method: 'POST',
    data
  });
}
